package com.winner.data.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.winner.data.exception.R;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 文件上传下载
 *
 * @author wangxinle5
 * @since 2023-01-03
 */
@Slf4j
@RestController
public class FileController extends BaseController {

    @Value("${file.path}")
    private String filePath;

    /**
     * 上传文件到指定目录下   localhost:8080/upload/picture
     * postman的body form-data来选择文件上传, 上传成功后, 返回url给前端
     *
     * @param file file
     * @param path path
     * @return 结果
     */
    @PostMapping(value = "/upload/{path}")
    public R upload(@RequestPart("file") MultipartFile file, @PathVariable("path") String path) {
        // 时间戳(精确到毫秒) + 5位随机数 作为批次号
        String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + StrUtil.DASHED
            + ThreadLocalRandom.current().nextInt(10000, 100000);

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf(StrUtil.DOT));
        // 雪花id 作为文件名 文件名相同也能上传成功
        String newFileName = IdUtil.getSnowflakeNextId() + extension;
        try {
            FileUtil.writeBytes(file.getBytes(), filePath + path + newFileName);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败");
        }
        return success(newFileName);
    }

    /**
     * 下载指定目录下的文件 localhost:8080/download/picture/1900007443505651712.jpg
     * postman下载pdf文件报错(点击send and download就是好的), 谷歌浏览器下载是ok的
     *
     * @param response response
     * @param fileName fileName
     */
    @GetMapping(value = "/download/{path}/{fileName}")
    public void download(HttpServletResponse response, @PathVariable String path, @PathVariable String fileName) {
        // JDK8特性 在try中声明了 InputStream、OutputStream，这种方式可以不用写finally去关闭stream，JDK会自动帮你去关闭stream。
        // IOUtils.closeQuietly(inputStream);
        String fileFullPath = filePath + path + StrUtil.SLASH + fileName;
        try (FileInputStream inputStream = new FileInputStream(fileFullPath);
            OutputStream outputStream = response.getOutputStream()) {
            response.addHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(new File(fileFullPath).getName(), "UTF-8"));
            IoUtil.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException("下载文件失败");
        }
    }

}
